import * as Stat from '@lib/stat';
import { ISearch, IWork } from '@lib/types';
import { userAs, userHref, workAs, workHref } from '@lib/url';
import { onCopy } from '@lib/utils';
import Voted from '@lib/voted';
import { Card, Icon, List } from 'antd';
import { ListGridType } from 'antd/lib/list';
import Link from 'next/link';
import * as React from 'react';
import Clipboard from 'react-clipboard.js';
import './index.less';

interface WorkListProps {
	list: (IWork | ISearch)[];
	grid?: ListGridType;
	hide_user?: boolean;
	hide_hot?: boolean;
	hide_vote?: boolean;
	hide_time?: boolean;
}

function isWork(object: any): object is IWork {
	return 'video' in object;
}

class WorkList extends React.Component<WorkListProps, any> {
	constructor(props: any) {
		super(props);
	}

	public async onVote(item: IWork) {
		if (Voted.is(item.id.toString())) {
			return;
		}
		Stat.vote(item.id);
		Voted.add(item.id.toString());
		item.vote++;
		this.forceUpdate();
	}

	public getDate(date_str: string) {
		const date = Date.parse(date_str + "+08:00");
		const current = new Date().getTime();
		const past = (current - date) / 1000;
		// 5分钟内
		if (past < 5 * 60) {
			return "刚刚";
		}
		// 一小时内
		if (past < 3600) {
			return Math.floor(past / 60) + "分钟前";
		}
		// 24小时
		if (past < 24 * 3600) {
			return Math.floor(past / 3600) + "小时前";
		}
		// 7天内
		if (past < 7 * 24 * 3600) {
			return Math.floor(past / 24 / 3600) + "天前";
		}
		return date_str.substr(date_str.indexOf('-') + 1);
	}

	render() {
		return (
			<List
				className="work-list"
				grid={this.props.grid || { gutter: 6, column: 1, lg: 2 }}
				dataSource={this.props.list}
				renderItem={item => {
					const actions = [];
					if (this.props.hide_user !== true) {
						actions.push(
							<Link href={userHref(item.user ? item.user.id : 0)} as={userAs(item.user ? item.user.id : 0)} key="user">
								<a><Icon type="user" />{item.user ? item.user.name : ""}</a>
							</Link>
						);
					}
					if (isWork(item) && this.props.hide_hot !== true) {
						actions.push(<span title="热度" key="hot"><Icon type="fire" />{item.hot / 10}</span>);
					}
					if (isWork(item) && this.props.hide_vote !== true) {
						actions.push(<span onClick={() => this.onVote(item)} key="vote"><Icon type="like" />{item.vote}</span>);
					}
					if (isWork(item) && this.props.hide_time !== true) {
						actions.push(<span title={item.update_time} key="time"><Icon type="history" />{this.getDate(item.update_time)}</span>);
					}
					return (
						<List.Item>
							<Card
								title={<Link href={workHref(item.id)} as={workAs(item.id)}><a className="black">{item.name}</a></Link>}
								extra={<Clipboard component="a" data-clipboard-text={item.code} onSuccess={() => onCopy("code", item.id)}>{item.code}</Clipboard>}
								actions={actions}
							>
								<div className="content" title={item.description}>{item.description}</div>
							</Card>
						</List.Item>
					)
				}}
			/>
		);
	}
}

export default WorkList;